/**
 * name:http服务
 * describe:对http请求做统一处理
 */
import {Injectable} from '@angular/core';
import {Headers, Http, RequestOptions, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';
import storage from './storage';
import SysData from './sysData';
import {HttpClient, HttpRequest, HttpResponse} from '@angular/common/http';
import {filter} from 'rxjs/operators';
import 'rxjs/add/operator/timeout';
import { TranslateService } from "@ngx-translate/core";
import * as FileSaver from "file-saver";
@Injectable()
export class BaseService {
    private httpClient:HttpClient;
    constructor(private http: Http,private translateService:TranslateService) {}
  /**
   * 统一发送请求
   * @param params
   * @returns {Promise<{success: boolean, msg: string}>|Promise<R>}
   */
  /**
   * get请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  public getInfo(url: string, params: any): any {
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded;;charset=UTF-8','ClientType':SysData.CLIENTTYPE,'lang':storage.get("defaultLang")||"zh"});
    let pa =params?"args="+JSON.stringify(params).replace(/\%/g,"%25").replace(/\//g,"%2F").replace(/\?/g,"%3F").replace(/\&/g,"%26").replace(/\=/g,"%3D").replace(/\#/g,"%23"):null;
    return this.http.get(url, {search: pa,headers:headers})
      .timeout(1800000000)//超时时间设置为1min
      .map(this.handleSuccess)
      .catch(res => this.handleError1(res));
  }
  /**
   * post请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  public postInfo(url: string, params: any,keepPlus?) {
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded;;charset=UTF-8','ClientType':SysData.CLIENTTYPE,'lang':storage.get("defaultLang")||"zh"});
    let options = new RequestOptions({ headers: headers });
    //特殊字符处理
    let pa ="args="+JSON.stringify(params).replace(/\%/g,"%25").replace(/\//g,"%2F").replace(/\?/g,"%3F").replace(/\&/g,"%26").replace(/\=/g,"%3D").replace(/\#/g,"%23");
    return this.http.post(url, pa,options )
      .timeout(1800000000)//超时时间设置为1min
      .map(this.handleSuccess)
      .catch(res => this.handleError1(res));
  }
  /**
   * 处理请求成功
   * @param res
   * @returns {{data: (string|null|((node:any)=>any)
 */
  private handleSuccess(res: Response) {
    //SysData.goodsUrl = "";
    const body = res['_body'];
    // console.log('接口返回的成功信息：' + res.json().result)
    if (body) { // 有数据返回
      return {
        data: res.json().result || {}, // 返回内容
        message: res.json().rspMsg || "", // 返回信息
        errCode: res.json().errCode ||"",
        statusText: '',
        status: JSON.parse(body).status == 1? 1: ""
      };
    } else { // 无数据返回
      return {
        data: res.json().result || {}, // 返回内容
        message: res.json().rspMsg || "", // 返回信息
        errCode: res.json().errCode ||"",
        statusText: '',
        status: ""
      };
    }
  }

  /**
   * 处理请求错误
   * @param error
   * @returns {void|Promise<string>|Promise<T>|any}
   */
  private handleError1(error: Response | any) {
    let errMsg: string;
    if (error.status === 404) {
      errMsg=this.translateService.instant('net_err')+','+this.translateService.instant('con_server');
    } else if (error.status === 500) {
      errMsg=this.translateService.instant('req_server_err');
    }else if (error.status === 504) {
      errMsg=this.translateService.instant('net_err')+','+this.translateService.instant('con_server');
    } else {
      errMsg=this.translateService.instant('net_err')+','+this.translateService.instant('cont_admin');
    }
    return Observable.throw(errMsg);
  }
}
